package LeetCode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//
// Created by ✎﹏ℳ๓独赏☆独醉 on 2024/4/27.
// 
public class 最接近的三数之和 {
    public static void main(String[] args) {
        int[] arr = {0,0,0};
        int target = 1;
        int res = threeSumClosest(arr,target);
        System.out.println(res);
    }
    static class ThreeSum{
        int firstNum;
        int secondNum;
        int thirdNum;
        int sum;
        public ThreeSum(int firstNum,int secondNum,int thirdNum){
            this.firstNum = firstNum;
            this.secondNum = secondNum;
            this.thirdNum = thirdNum;
            this.sum = firstNum + secondNum + thirdNum;
        }
    }
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        ThreeSum res = null;
        for (int i = 0; i < nums.length-2; i++) {
            int left = i + 1, right = nums.length - 1;
            ThreeSum temp = new ThreeSum(nums[i], nums[left], nums[right]);
            if(res==null){
                res = temp;
            }
            while (left < right-1) {
                if (temp.sum == target) {
                    res = temp;
                    return res.sum;
                } else if (temp.sum > target) {
                    right--;
                    while (left < right && nums[right] == nums[right + 1]) right--;
                } else {
                    left++;
                    while (left < right && nums[left] == nums[left - 1]) left++;
                }
                temp = new ThreeSum(nums[i], nums[left], nums[right]);
            }
            if (Math.abs(target - temp.sum) < Math.abs(target - res.sum)) {
                res = temp;
            }
        }
        return res.sum;
    }




//    if(Math.abs(nums[left] + nums[right] + nums[i]) > target || Math.abs(nums[left] + nums[right] + nums[i]) >= res.sum){
//        if(nums[left] + nums[right] + nums[i] > 0){
//            right--;
//            while (right > 0 && nums[right] == nums[right + 1]) right--;
//        }else {
//            left++;
//            while (left < right && nums[left] == nums[left - 1]) left++;
//        }
//    }else{
//        res = new ThreeSum(nums[i],nums[left],nums[right]);
//    }
}
